package com.aiti.myproject.server;

import java.util.Date;
import java.util.List;

import com.google.appengine.api.blobstore.BlobstoreService;
import com.google.appengine.api.blobstore.BlobstoreServiceFactory;
import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;
import com.aiti.myproject.client.service.UserImageService;
import com.aiti.myproject.shared.Tag;
import com.aiti.myproject.shared.UploadImage;

public class UserImageServiceImpl extends RemoteServiceServlet implements UserImageService{

	private static final long serialVersionUID = 1L;

	@Override
	public String getBlobstoreUploadUrl() {
		BlobstoreService blobstoreService = BlobstoreServiceFactory.getBlobstoreService();
		// /upload
		return blobstoreService.createUploadUrl("/upload");
	}

	@Override
	public UploadImage get(String key) {
		UploadedImageDAO imageDAO = new UploadedImageDAO();
		UploadImage image = imageDAO.get(key);
		return image;
	}

	@Override
	public List<UploadImage> getRecentlyUploaded() {
		UploadedImageDAO imageDAO = new UploadedImageDAO();
		List<UploadImage> images = imageDAO.getRecent();
		return images;
	}

	@Override
	public void deleteImage(String key) {
		UserService userService = UserServiceFactory.getUserService();
		User user = userService.getCurrentUser();
		UploadedImageDAO imageDAO = new UploadedImageDAO();
		if(user.getUserId().equals(imageDAO.get(key).getOwnerId())){
			imageDAO.delete(key);
		}
	}
	
	public String tagImage(Tag tag) {
		UserService userService = UserServiceFactory.getUserService();
		User user = userService.getCurrentUser();
		TagDAO tagDAO = new TagDAO();

		tag.setTagId(user.getUserId());
		tag.setCreateAt(new Date());

		String key = tagDAO.put(tag);
		return key;
	}

	@Override
	public List<Tag> getTagsForImage(UploadImage image) {
		TagDAO tagDAO = new TagDAO();
		List<Tag> tags = tagDAO.getForImage(image);
		return tags;
	}

}
